import java.util.Arrays;

/**
 * @Author ZhangCuirong
 * @Date 2025/9/9 10:54
 * @description:
 */
public class Solution16 {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int delta = Integer.MAX_VALUE;
        int res = 0;
        for (int i = 0; i < nums.length - 2; i++) {
            int a = nums[i];
            int sum = twoSumClosest(nums, target - a, i + 1);
            if (Math.abs(a + sum - target) < delta) {
                delta = Math.abs(a + sum - target);
                res = a + sum;
            }
        }
        return res;
    }

    public int twoSumClosest(int[] nums, int target, int start) {
        int left = start, right = nums.length - 1;
        int delta = Integer.MAX_VALUE;
        int res = 0;
        while (left < right) {
            if (Math.abs(nums[left] + nums[right] - target) < delta) {
                delta = Math.abs(nums[left] + nums[right] - target);
                res = nums[left] + nums[right];
            }
            if (nums[left] + nums[right] < target) {
                left++;
            } else if (nums[left] + nums[right] > target) {
                right--;
            } else {
                return nums[left] + nums[right];
            }
        }
        return res;
    }

    public static void main(String[] args) {
        Solution16 solution = new Solution16();
        System.out.println(solution.threeSumClosest(new int[]{-1, 2, 1, -4}, 1));
        System.out.println(solution.threeSumClosest(new int[]{0, 0, 0}, 1));
    }
}
